﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// 时间限制器：
/// 漏洞
/// 1:删除unitydebug文件，清空playerprefs，修改系统时间为2020-11-10日至EndTime之间可正常使用 
/// </summary>
public class Password : MonoBehaviour
{
    public PrefsTime EndTime;
    public List<PswList> pl; 
    public string TimeOriStr;
    public string TimeDeCodeStr; 
    /// <summary>
    /// 系统时间
    /// </summary>
    public DateTime NowTime;
    /// <summary>
    /// 最早打开时间默认为今天
    /// </summary>
    public PrefsTime 储存时间;
    bool ALLOW_ALL=false;

    public GameObject TipsUI;
    private void Start()
    {
        Path = Application.streamingAssetsPath+ "/DebugUpdate.UnityDebug"; 
        Read_Time();
        StartCoroutine(Continue_Check_Time());
    }

    [ContextMenu("aaa")]
    public void aaa() 
    {
        Debug.Log(DateTime.Now);
    }

    private void Update()
    {
        
    }
    void ReadPrefs(bool read = true)
    {
        if (read)
        {
            储存时间.year = PlayerPrefs.GetInt("Year");
            储存时间.month = PlayerPrefs.GetInt("Month");
            储存时间.day = PlayerPrefs.GetInt("Day");
            储存时间.hour = PlayerPrefs.GetInt("Hour");
            储存时间.min = PlayerPrefs.GetInt("Minute");
            储存时间.second = PlayerPrefs.GetInt("Second");
            TimeDeCodeStr = 储存时间.year + "-" + 储存时间.month + "-" + 储存时间.day + "-" + 储存时间.hour + "-" + 储存时间.min + "-" + 储存时间.second;
            print(TimeDeCodeStr);
        }
        else
        {
            PlayerPrefs.SetInt("Year", 储存时间.year);
            PlayerPrefs.SetInt("Month", 储存时间.month);
            PlayerPrefs.SetInt("Day", 储存时间.day);
            PlayerPrefs.SetInt("Hour", 储存时间.hour);
            PlayerPrefs.SetInt("Minute", 储存时间.min);
            PlayerPrefs.SetInt("Second", 储存时间.second);
        }
    }
    void Check()
    {
        
        if (TimeDeCodeStr == "" || TimeDeCodeStr == null)
        {
            TimeDeCodeStr = "2020-11-10-13-30-10"; 
            TimeOriStr = Translator(TimeDeCodeStr, false);
        }
        if(储存时间.year==0)
        {
            储存时间.year = 2020;
            储存时间.month = 11;
            储存时间.day = 10;
            储存时间.hour = 13;
            储存时间.min = 30;
            储存时间.second = 10;
        }
        foreach(PswList p in pl)
        {
            if (TimeOriStr.Contains(p.num.ToString()))
            {
                ReadPrefs();
                print("修改了文件内容");
                if (TipsUI != null)
                    TipsUI.SetActive(true);
                Time.timeScale = 0;
                return;
            }
        }
        if (TimeDeCodeStr == "2077-01-01-01-01-01")
        {
            ALLOW_ALL = true;
            print("解锁成功");
            Time.timeScale = 1;
            if (TipsUI != null)
                TipsUI.SetActive(false);
            return;
        }
        else
        {
            try
            {
                int state= TimeJudge();
                if (state == 0)
                {
                    string[] datetime = TimeDeCodeStr.Split('-');
                    int year = int.Parse(datetime[0]);
                    int month = int.Parse(datetime[1]);
                    int day = int.Parse(datetime[2]);
                    int hour = int.Parse(datetime[3]);
                    int minute = int.Parse(datetime[4]);
                    int second = int.Parse(datetime[5]);
                    储存时间.year = year;
                    储存时间.month = month;
                    储存时间.day = day;
                    储存时间.hour = hour;
                    储存时间.min = minute;
                    储存时间.second = second;
                    print("超时或修改了系统时间");
                    //Time.timeScale = 0;
                    //TipsUI?.SetActive(true);

                    //220903到期闪退
#if UNITY_EDITOR
                    EditorApplication.isPlaying = false;
#else
                    Application.Quit();
#endif
                }
                else
                {
                    TimeDeCodeStr = NowTime.Year + "-" + NowTime.Month + "-" + NowTime.Day + "-" + NowTime.Hour + "-" + NowTime.Minute + "-" + NowTime.Second;
                    储存时间.year = NowTime.Year;
                    储存时间.month = NowTime.Month;
                    储存时间.day = NowTime.Day;
                    储存时间.hour = NowTime.Hour; 
                    储存时间.min = NowTime.Minute; 
                    储存时间.second = NowTime.Second;
                    print("未超时");
                    if (TipsUI != null)
                        TipsUI.SetActive(false);
                    Time.timeScale = 1;
                }
            }
            catch(Exception e)
            {
                if(TipsUI != null)
                    TipsUI.SetActive(true);
                Time.timeScale = 0;
                ReadPrefs();
                print("可能修改了文件内容或者损坏了文件");

                //220903到期闪退
#if UNITY_EDITOR
                EditorApplication.isPlaying = false;
#else
                    Application.Quit();
#endif
            }
        }
    }

    /// <summary>
    /// 0-ERROR  1-CONFIRM
    /// </summary>
    /// <returns></returns>
    int TimeJudge()
    {
        int state = 1;

        string[] datetime = TimeDeCodeStr.Split('-');
        int year = int.Parse(datetime[0]);
        int month = int.Parse(datetime[1]);
        int day = int.Parse(datetime[2]);
        int hour = int.Parse(datetime[3]);
        int minute = int.Parse(datetime[4]);
        int second = int.Parse(datetime[5]);

        NowTime = DateTime.Now;
        if (NowTime.Year < year)
        {
            state=0;
        }
        else if(NowTime.Year==year)
        {
            if (NowTime.Month < month)
            {
                state = 0;
            }
            else if (NowTime.Month == month)
            {
                if (NowTime.Day < day)
                {
                    state = 0;
                }
                else if (NowTime.Day == day)
                {
                    if (NowTime.Hour < hour)
                    {
                        state = 0;
                    }
                    else if (NowTime.Hour == hour)
                    {
                        if (NowTime.Minute < minute)
                        {
                            state = 0;
                        }
                        
                    }
                }
            } 
        }
        else
        {
            if (NowTime.Year > EndTime.year)
            {
                state = 0; 
            }
            else if (NowTime.Year == EndTime.year)
            {
                if (NowTime.Month > EndTime.month)
                {
                    state = 0;
                }
                else if (NowTime.Month == EndTime.month)
                {
                    if (NowTime.Day > EndTime.day)
                    {
                        state = 0;
                    }
                    else if (NowTime.Day == EndTime.day)
                    {
                        if (NowTime.Hour > EndTime.hour)
                        {
                            state = 0;
                        }
                        else if (NowTime.Hour == EndTime.hour)
                        {
                            if (NowTime.Minute > EndTime.min)
                            {
                                state =0;
                            }
                        }
                    }
                }
            }
        }

        return state;
    }

    string Translator(string TimeStr, bool ToNormal = true)
    {

        string Time_Translated = TimeStr;

        if (ToNormal)
        {
            foreach (PswList p in pl)
            {
                Time_Translated= Time_Translated.Replace(p.word, p.num);
            }
        }
        else
        {
            foreach (PswList p in pl)
            {
                Time_Translated= Time_Translated.Replace(p.num, p.word);
            }
        } 
        return Time_Translated;
    }
    string Path;

    public void Write_Time()
    {
        if (!File.Exists(Path))
        {
            File.Create(Path).Dispose();
        }
        TimeOriStr = Translator(TimeDeCodeStr,false);
        File.WriteAllText(Path, TimeOriStr);
    }
    public void Read_Time()
    {
        if (!File.Exists(Path))
        {
            Write_Time();

            Debug.LogError("读取的文件不存在！已创建一个新文件"); 
        }
        else
        {
            TimeOriStr = File.ReadAllText(Path);
            TimeDeCodeStr = Translator(TimeOriStr);
        }
    }

    IEnumerator Continue_Check_Time()
    {
        while (true)
        {
            Check();
            yield return new WaitForSeconds(60*60);
        }
    }

    private void OnApplicationQuit()
    {   
        if (!ALLOW_ALL)
        {
            Write_Time();
            ReadPrefs(false);
        }
    }
}
[Serializable]
public class PswList
{
    public char num;
    public char word;
}
[Serializable]
public class PrefsTime
{
    public int year;
    public int month;
    public int day;
    public int hour;
    public int min;
    public int second;
}
